package inc.unlocked.dao.impl;


import inc.unlocked.dao.GenericDAO;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collection;
import java.util.List;

/**
 * User: MTolstykh
 * Date: 12.12.11
 * Time: 12:01
 */
public class GenericDAOImpl<ENTITY, ID extends Serializable> extends HibernateDaoSupport
        implements GenericDAO<ENTITY, ID> {

    protected final Class<?> ENTITY_CLASS;

    @SuppressWarnings("unchecked")
    public GenericDAOImpl() {
        ParameterizedType parameterizedType = (ParameterizedType) getClass().getGenericSuperclass();
        ENTITY_CLASS = (Class) parameterizedType.getActualTypeArguments()[0];
    }

    @SuppressWarnings("unchecked")
    public ENTITY findById(ID id) {
        return (ENTITY) getHibernateTemplate().get(ENTITY_CLASS, id);
    }

    @SuppressWarnings("unchecked")
    public List<ENTITY> findAll() {
        return (List<ENTITY>) getHibernateTemplate().loadAll(ENTITY_CLASS);
    }

    @SuppressWarnings("unchecked")
    public void save(ENTITY entity) {
        getHibernateTemplate().save(entity);
    }

    @SuppressWarnings("unchecked")
    public void delete(ENTITY entity) {
        getHibernateTemplate().delete(entity);
    }

    @SuppressWarnings("unchecked")
    public void deleteAll(Collection<ENTITY> entities) {
        getHibernateTemplate().deleteAll(entities);
    }

    @SuppressWarnings("unchecked")
    public void saveOrUpdate(ENTITY entity) {
        getHibernateTemplate().saveOrUpdate(entity);
    }
}
